<template>
  <div class="yoyo-container mx-auto pb-[env(safe-area-inset-bottom)]">
    <navBar :title="$t('products.payNavTitle')" />

    <!-- Content -->
    <div class="pay-content">
      <AddressForm ref="addressForm" :addressData="addressData" :showAddress="showAddress" @register-check="handleRegisterCheck" />
      <PayProduct :products="settleProducts" />
      <PaymentSummary :priceInfo="settlementData.price" :settlementDataErrCode="settlementDataErrCode" @yoyo-used="handleYoYoUsed" @coupon-selected="handleCouponSelected" />
      <PaymentMethod :bankInfo="bankData" ref="paymentMethod" @payment-method-change="handlePaymentMethodChange" />
    </div>
    <div class="h-17"></div>

    <!-- 结算按钮 -->
    <div class="fixed z-50 h-17 bottom-0 left-0 right-0 pb-[env(safe-area-inset-bottom)] yoyo-container mx-auto">
      <div class="flex items-center space-x-3 w-full h-17 lg:mx-4 lg:w-[calc(100%-2rem)] bg-white border-t border-gray-200 py-3 px-3">
        <div class="flex-1 text-right mr-4">
          <div class="text-lg font-bold text-[#ff7a00]">RM {{ formatToYuan(settlementData.price && settlementData.price.payPrice) }}</div>
          <div class="text-sm text-gray-500" v-if="isRegister != null && !isLoggedIn">
            <div v-if="isRegister == false" class="flex items-center justify-end">
              <van-button type="primary" size="mini" plain color="#ff7a00" @click="handleLogin">
                {{ $t("products.registerMember") }}
              </van-button>
              <span class="ml-1">{{ $t("products.registerMemberDiscount") }}</span>
            </div>
            <div v-if="isRegister == true" class="flex items-center justify-end">
              <van-button type="primary" size="mini" plain color="#ff7a00" @click="handleLogin">
                {{ $t("products.loginMember") }}
              </van-button>
              <span class="ml-1">{{ $t("products.loginMemberDiscount") }}</span>
              <span>{{ settlementData.givePoint }}</span>
              <span>{{ $t("products.yoyoCoins") }}</span>
            </div>
          </div>
        </div>

        <!-- 结算按钮 -->
        <van-button type="primary" class="rounded-xl w-24 h-8" color="#ff7a00" @click="handleCheckout">
          {{ $t("products.checkout") }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import AddressForm from "@/components/products/AddressForm.vue"
import PayProduct from "@/components/products/PayProduct.vue"
import PaymentSummary from "@/components/products/PaymentSummary.vue"
import PaymentMethod from "@/components/products/PaymentMethod.vue"
import { mapGetters, mapMutations } from "vuex"
import { getDefaultAddress, getDefaultBank, getSettlement, createOrder, payOrder } from "@/apis/pay"

import { formatToYuan } from "@/utils/common"

export default {
  name: "Pay",
  components: {
    AddressForm,
    PayProduct,
    PaymentSummary,
    PaymentMethod,
  },
  data() {
    return {
      backSrc: require("@/assets/images/back.png"),
      yoyoUsed: false, //是否使用YoYo币
      couponId: "", //优惠券id
      paymentData: null,
      addressData: null,
      bankData: null,
      showAddress: false,
      settleProducts: [], //结算商品
      settlementData: {},
      isRegister: null,
      formatToYuan,
      isLoading: false,
      settlementDataErrCode: '',
    }
  },
  computed: {
    ...mapGetters({
      isZh: "lang/isZh",
      isLoggedIn: "auth/isLoggedIn",
    }),
  },
  methods: {
    ...mapMutations({
      setLoginDialogVisible: "auth/SET_LOGIN_DIALOG_VISIBLE",
    }),
    handleYoYoUsed(discount, isRefresh) {
      this.yoyoUsed = discount
      if (isRefresh) {
        this.getSettlementData()
      }
    },
    handleCouponSelected(coupon, isRefresh) {
      this.couponId = coupon
      if (isRefresh) {
        this.getSettlementData()
      }
    },
    handlePaymentMethodChange(paymentData) {
      this.paymentData = paymentData
      console.log("Payment method changed:", paymentData)
    },
    async handleCheckout() {
      if (this.isLoading) return

      // 验证地址表单
      if (!this.$refs.addressForm.validateForm()) {
        this.$toast(this.$t("products.completeShippingInfo"))
        return
      }

      // 验证支付方式
      if (!this.$refs.paymentMethod.validatePayment()) {
        this.$toast(this.$t("products.completePaymentInfo"))
        return
      }

      // 获取地址数据
      const addressData = this.$refs.addressForm.getFormData()

      // 获取支付数据
      const paymentData = this.$refs.paymentMethod.getPaymentData()

      const items = this.settleProducts.map((item) => {
        return {
          skuId: item.sku,
          count: item.quantity,
          cartId: item.cartId || "",
        }
      })
      const params = {
        items: items, // 商品信息
        couponId: this.couponId || "", // 优惠券id
        usePoint: this.yoyoUsed ? "1" : "0", // 是否使用YoYo币
        receiverAddress: addressData.address, // 收获地址
        receiverName: addressData.name, // 收获人姓名
        receiverMobile: addressData.mobile, // 收获人手机号
        email: addressData.email, // 收获人邮箱
        receivePromotion: addressData.subscribeMarketing ? addressData.email : "", // 是否订阅促销
        bankName: paymentData.form.name, // 银行卡名称
        bankCardNo: paymentData.form.cardNo, // 银行卡号
        bankExpireDate: paymentData.form.expireDate, // 有效期
        bankChecksum: paymentData.form.checksum, // 校验码
        bankSave: false, // 是否保存银行卡
      }
      try {
        this.isLoading = true
        const orderData = await createOrder(params)
        console.log("订单数据:", orderData)
        window.open(orderData.data, '_blank')
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },
    async getDefaultData() {
      if (!this.isLoggedIn) {
        return
      }
      try {
        const addressData = await getDefaultAddress()
        const bankData = await getDefaultBank()
        this.addressData = addressData.data
        this.bankData = bankData.data
      } catch (error) {
        console.log(error)
      }
    },
    async getSettlementData() {
      try {
        const items = this.settleProducts.map((item) => {
          return {
            skuId: item.sku,
            count: item.quantity,
            cartId: "",
          }
        })
        const params = {
          items: items,
          couponId: this.couponId || "",
          usePoint: this.yoyoUsed ? "1" : "0",
          receiverAddress: "",
        }
        const res = await getSettlement(params)
        this.settlementData = res.data
      } catch (error) {
        const code = error.code
        // this.settlementDataErrCode = code
        if (typeof this.settlementDataErrCode === 'string') {
          this.settlementDataErrCode = code - 0
        } else {
          this.settlementDataErrCode = code + ''
        }
      }
    },
    handleRegisterCheck(isRegister) {
      this.isRegister = isRegister
    },
    handleLogin() {
      this.setLoginDialogVisible(true)
    },
  },
  watch: {
    // yoyoUsed(val) {
    //   this.getSettlementData()
    // },
    // couponId() {
    //   this.getSettlementData()
    // },
  },
  created() {
    this.getDefaultData()
    this.settleProducts = JSON.parse(localStorage.getItem("yoyotravel_settleData"))

    // 遍历this.settleData中的type判断是sim还是esim ,如果有sim, showAddress=true
    this.settleProducts.forEach((item) => {
      if (item.type === "sim") {
        this.showAddress = true
      }
    })
    this.getSettlementData()
  },
}
</script>

<style scoped></style>
